#include "recv.h"
// 每个火车箱接多少个字节
#define TRAIN_SIZE 10240
// 文件地址
#define FILE_PATH "/home/lijie/Linux/百度云C/baidu_cloud_v3/cloud-storage-3/user_file_content/"

// 火车箱

char file_data[TRAIN_SIZE];

int recv_n(int fd, void *buf, int len)
{
    int recvLen = 0;
    int ret = 0;
    while (recvLen < len)
    {
        ret = recv(fd, buf + recvLen, len - recvLen, 0);
        if (ret == -1)
        {
            perror("recv");
            return -1;
        }
        else if (ret == 0)
        {

            LOG_INFO("client close\n");
            return 0;
        }
        recvLen += ret;
    }
    return recvLen;
}

train_t train;
// 接收文件
int recv_file(int fd, char *filename, ssize_t fileSize)
{
    // 拼接文件地址和文件名
    char file_path[1024] = {0};
    strcpy(file_path, FILE_PATH);
    strcat(file_path, filename);
    // 创建文件
    int fd_file = open(file_path, O_CREAT | O_WRONLY, 0666);
    LOG_INFO("create file %s success\n", file_path);
    LOG_INFO("fd_file = %d\n", fd_file);
    ERROR_CHECK(fd_file, -1, "open");

    LOG_INFO("fliesize ret = %d\n", fileSize);
    // 接收文件内容
    ssize_t ret = 0;
    ssize_t currentSize = 0;
    ssize_t write_len = 0;
    // while (1)
    // {
    //     ret = recv_n(fd, file_data, TRAIN_SIZE);
    //     currentSize += ret;
    //     LOG_INFO("ret = %d,currentSize = %d\n", ret, currentSize);
    //     if (ret == 0 || currentSize == fileSize)
    //     {
    //         break;
    //     }
    //     write(fd_file, file_data,ret);

    // }
    // 接收文件内容
    while (currentSize < fileSize)
    {
        ssize_t to_read = (fileSize - currentSize) > TRAIN_SIZE ? TRAIN_SIZE : (fileSize - currentSize);

        ret = recv_n(fd, file_data, to_read);
        if (ret <= 0)
        {
            if (ret < 0)
            {
                perror("recv_n");
                close(fd_file);
                LOG_ERROR("recv_n error\n");
            }
            break;
        }

        char *write_ptr = file_data;
        ssize_t remaining = ret;

        while (remaining > 0)
        {
            write_len = write(fd_file, write_ptr, remaining);
            if (write_len == -1)
            {
                if (errno == EINTR)
                    continue;
                perror("write");
                close(fd_file);
                return -1;
            }
            remaining -= write_len;
            write_ptr += write_len;
        }

        currentSize += ret;
        LOG_INFO("ret = %ld, currentSize = %ld\n", ret, currentSize);
    }

    close(fd_file);

    if (currentSize == fileSize)
    {
        LOG_INFO("put file %s success\n", filename);
        return 0;
    }
    else
    {
        LOG_ERROR("put file %s incomplete, received %ld/%ld\n",
                  filename, currentSize, fileSize);
        // 删除不完整的文件
        unlink(file_path);
        return -1;
    }

close(fd_file);
LOG_INFO("put file %s success\n", filename);
return 0;
}